#include "str.h"
#include <cstring>
#include <cstdlib>

using namespace std;

char *apple(const char *src, int length, const char *begin, const char *end)
{
    size_t beginLength = strlen(begin);
    size_t endLength = strlen(end);
    int lineCount = line_count(src);
    int resultSize = length + lineCount * (beginLength + endLength);
    char *result = (char *)malloc(resultSize * sizeof(char));

    char *res = result;
    const char *p = src;
    bool lineBegin = true;
    while (*p)
    {
        if (lineBegin)
        {
            strcpy(res, begin);
            res += beginLength;
            lineBegin = false;
        }

        if (*p == '\r' && *(p + 1) == '\n')
        {
            strcpy(res, end);
            res += endLength;
            *res = '\r';
            *(++res) = '\n';
            ++res;
            lineBegin = true;
            p += 2;
        }
        else if (*p == '\n')
        {
            strcpy(res, end);
            res += endLength;
            *res = '\n';
            ++res;
            lineBegin = true;
            ++p;
        }
        else
        {
            *res = *p;
            ++res;
            ++p;
        }
    }
    if (!lineBegin)
    {
        strcpy(res, end);
    }

    return result;
}

int line_count(const char *src)
{
    const char *result = src;
    int lineCount = 1;
    while ((result = strchr(result, '\n')) != NULL)
    {
        lineCount++;
        ++result;
    }

    return lineCount;
}

void to_single_line(char *src)
{
    char *p = src;
    char *q = src;
    while (*p)
    {
        *q = *p;
        if (*q == '\r' || *q == '\n')
        {
            ++p;
        }
        else
        {
            ++p;
            ++q;
        }
    }
    while (q < p)
    {
        *q = 0;
        ++q;
    }
}
